package com.lyx.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lyx.entity.User;
import com.lyx.handler.BusinessException;
import com.lyx.mapper.UserMapper;
import com.lyx.response.ResultCode;
import com.lyx.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lyx.utils.JwtUtil;
import com.lyx.utils.MD5Utils;

import com.lyx.vo.UserVO;
import jdk.nashorn.internal.parser.Token;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author com.lyx
 * @since 2022-03-02
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Override
    public Page<User> findUserList(Page<User> page, UserVO userVO) {
        List<User> userList = this.baseMapper.findUserList(page, userVO);
        page.setRecords(userList);
        return page;
    }

    @Override
    public void exportUserExcel(HttpServletResponse response, List<User> users) throws IOException {
        //----- 写入excel文件
            String exportFileName = "TbUserInfo.xlsx";
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/vnd.ms-excel");
        response.addHeader("Content-Disposition", "attachment;filename=" + exportFileName);
        EasyExcel.write(response.getOutputStream(), User.class)
                .sheet("用户信息")
                //自动列宽
                .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
                .doWrite(users);
    }

    @Override
    public String login(String username, String password) {
        User user = this.baseMapper.loadUserByUsername(username);
        String token = null;
        if(user!=null){
            String salt = user.getSalt();
            String userPassword= user.getPassword();
            //加密加盐
            String encryptionPassword = MD5Utils.md5Encryption(password, salt);
            if (userPassword.equals(encryptionPassword)){
                HashMap<String, Object> userMap = new HashMap<>();
                userMap.put("username",username);
                userMap.put("password",password);
                token = JwtUtil.createToken(userMap);
            }   else {
             throw new BusinessException(ResultCode.USER_CREDENTIALS_ERROR.getCode(),
                     ResultCode.USER_CREDENTIALS_ERROR.getMessage());
            }

        }else {
            throw  new BusinessException(ResultCode.USER_ACCOUNT_NOT_EXIST.getCode(),
                    ResultCode.USER_ACCOUNT_NOT_EXIST.getMessage());
        }
        return token;
    }
}
